import React from 'react';
import Picker from 'rmc-picker';
import { addZero } from '../util';
import s from '../index.m.less';

export default class DatePicker extends React.Component {
    static defaultProps = {
        type: 'hour', // "datetime"年月日时分, "date"年月日, "time"时分, "hour"年月日时
        timeStamp: 0,
        beginYear: new Date().getFullYear(),
        endYear: new Date().getFullYear() + 4,
        title: '',
        onChange: () => {},
        cancel: () => {},
        cancelName: '取消',
        confirm: () => {},
        confirmName: '确定',
        endTime: null, // 键盘结束时间
    };

    constructor(p) {
        super(p);
        const date = new Date(this.props.timeStamp * 1000);
        // 此乃记录的时间
        this.state = {
            year: date.getFullYear(),
            month: date.getMonth() + 1,
            day: date.getDate(),
            hour: date.getHours(),
            minute: date.getMinutes(),
        };
        this.initTime = { ...this.state };
    }

    // 控制数字
    handleChange = unit => value => {
        this.setState({ [unit]: value });
    };

    // 生成准确的年
    formatYear = index => {
        if (this.initTime.year < this.props.beginYear) {
            return this.initTime.year + index;
        }
        return this.props.beginYear + index;
    };

    calcLength = unit => {
        const { beginYear, endTime } = this.props;
        const { year, month } = this.state;
        switch (unit) {
            case 'minute':
                return 60;
            case 'hour':
                return 24;
            case 'day':
                if (
                    endTime
                    && year == new Date(endTime * 1000).getFullYear()
                    && month - 1 == new Date(endTime * 1000).getMonth()
                ) {
                    return new Date(endTime * 1000).getDate();
                }

                return new Date(year, month, 0).getDate();
            case 'month':
                if (endTime && year == new Date(endTime * 1000).getFullYear()) {
                    return new Date(endTime * 1000).getMonth() + 1;
                }
                return 12;
            case 'year':
                if (endTime) {
                    return new Date(endTime * 1000).getFullYear() - beginYear + 1;
                }
                return Math.max(this.props.endYear - this.initTime.year, 5);
            default:
                return 0;
        }
    };

    submit = () => {
        const {
            year, month, day, hour, minute
        } = this.state;
        this.props.confirm
            && this.props.confirm(parseInt(new Date(year, month - 1, day, hour, minute).getTime() / 1000));
        this.props.close && this.props.close();
    };

    renderUnit = unit => {
        switch (unit) {
            case 'time':
                return ['时', '分'].map(i => <div key={i}>{i}</div>);
            case 'date':
                return ['年', '月', '日'].map(i => <div key={i}>{i}</div>);
            case 'hour':
                return ['年', '月', '日', '时'].map(i => <div key={i}>{i}</div>);
            case 'datetime':
                return ['年', '月', '日', '时', '分'].map(i => <div key={i}>{i}</div>);
            default:
                return null;
        }
    };

    renderPicker = type => {
        const {
            year, month, day, hour, minute
        } = this.state;
        switch (type) {
            case 'time':
                return [this.renderPickerItem(hour, 'hour'), this.renderPickerItem(minute, 'minute')];
            case 'date':
                return [
                    this.renderPickerItem(year, 'year'),
                    this.renderPickerItem(month, 'month'),
                    this.renderPickerItem(day, 'day'),
                ];
            case 'hour':
                return [
                    this.renderPickerItem(year, 'year'),
                    this.renderPickerItem(month, 'month'),
                    this.renderPickerItem(day, 'day'),
                    this.renderPickerItem(hour, 'hour'),
                ];
            case 'datetime':
                return [
                    this.renderPickerItem(year, 'year'),
                    this.renderPickerItem(month, 'month'),
                    this.renderPickerItem(day, 'day'),
                    this.renderPickerItem(hour, 'hour'),
                    this.renderPickerItem(minute, 'minute'),
                ];
            default:
                return null;
        }
    };

    renderPickerItem = (value, timeUnit) => (
        <Picker
            key={timeUnit}
            className={s.picker}
            selectedValue={value}
            onValueChange={this.handleChange(timeUnit)}
            defaultSelectedValue={this.initTime[timeUnit]}
        >
            {Array.from({ length: this.calcLength(timeUnit) }).map((i, index) => (
                <Picker.Item
                    value={
                        timeUnit === 'year'
                            ? this.formatYear(index)
                            : ['month', 'day'].includes(timeUnit)
                                ? index + 1
                                : index
                    }
                    key={index}
                >
                    {timeUnit === 'year'
                        ? this.formatYear(index)
                        : addZero(['month', 'day'].includes(timeUnit) ? index + 1 : index)}
                </Picker.Item>
            ))}
        </Picker>
    );

    render() {
        const {
            cancelName, confirmName, title, type
        } = this.props;
        return (
            <div className={s.layer}>
                <div className={s.header}>
                    <button
                        className={`${s.cancel} modal-close`}
                        onClick={() => {
                            this.props.cancel && this.props.cancel();
                        }}
                    >
                        {cancelName}
                    </button>
                    <div className={s.title}>{title}</div>
                    <button className={s.confirm} onClick={this.submit}>
                        {confirmName}
                    </button>
                </div>
                <div className={s.unitBanner}>{this.renderUnit(type)}</div>
                <div className={s.pk}>{this.renderPicker(type)}</div>
            </div>
        );
    }
}
